﻿using System;
using System.IO;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using SilverlightWebcamEncoder.Messages;

namespace SilverlightWebcamEncoder.ViewModels
{
    public class PlaybackViewModel : ViewModelBase
    {
        private string m_encodedFilePath;

        public PlaybackViewModel()
        {
            Messenger.Default.Register<CapturedMediaReady>(this, OnCapturedMediaReady);
            ClosePlayback = new RelayCommand(OnClosePlayback);

            Messenger.Default.Register<LocalVideoFilenameRequest>(this, OnLocalVideoFilenameRequest);
        }

        private void OnLocalVideoFilenameRequest(LocalVideoFilenameRequest e)
        {
            e.FilePath = EncodedFilePath;
        }

        private void OnClosePlayback()
        {
            string encodedPath = EncodedFilePath;

            /* Closes file so we can delete it */
            EncodedFilePath = "";

            try
            {
                if(!string.IsNullOrEmpty(encodedPath))
                File.Delete(encodedPath);
            }
            catch (Exception)
            {
                throw;
            }

            Messenger.Default.Send(new PlaybackClosed());
        }

        public ICommand ClosePlayback
        {
            get; private set;
        }

        public void OnCapturedMediaReady(CapturedMediaReady capturedMediaInfo)
        {
            EncodedFilePath = capturedMediaInfo.EncodedFilePath;
        }

        public string EncodedFilePath
        {
            get { return m_encodedFilePath; }
            set
            {
                m_encodedFilePath = value;
                RaisePropertyChanged("EncodedFilePath");
            }
        }
    }
}
